﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
using PlugNT.Custom;
using PlugNT.Cms.Core;
using PlugNT.Cms.Page;
using PlugNT.Cms.BLL;
using PlugNT.Cms.Model;

namespace PlugNT.Cms.Web.Admin.Pre_Article
{
    public partial class Add : AdminPage
    {
        private Category curCategory = new Category();
        private Field curField = new Field();
        private Article curArticle = new Article();
        private Channel curChannel = new Channel();
        private Tables curTables = new Tables();
        private const string bindtag = "bindtag";

        private string currpostfix = "";
        //public string jsonString = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //权限检测
            this.CheckPower();

            currpostfix = (Request.QueryString["currpostfix"] == null) ? WebConfig.TablePostfix : Request.QueryString["currpostfix"].Trim();
            curArticle.CurPostfix = currpostfix;
            if (!IsPostBack)
            {
                //绑定数据
                Data_bind();
            }

        }

        protected void imgBtnSubmit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {

            TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
            ArticleInfo model = new ArticleInfo();

            string images = this.txtpic.Text;
            string title = this.txttitle.Text;
            string subtitle = this.txtsubtitle.Text;
            string jumpurl = (this.jumpurl_on_of.Checked) ? this.jumpurl.Text.Trim() : "";
            string[] clsArr = this.ddlMenu.SelectedValue.Trim().Split('-');
            bool flag = true;
            string errorMessage = "录入新闻--<b>[" + title + "]</b>--失败！&z=no";

            if (tinfo != null)
            {
                if (clsArr.Length == 3)
                {
                    string clslist = clsArr[0];
                    string clsno = clsArr[1];
                    bool isbindtmp = (clsArr[2] == bindtag);

                    //生成路径
                    string createpath = txtcreatepath.Text.Trim();
                    string t_createpath = "";
                    string t_showfile = "";

                    Templet tmpTemplet = new Templet();
                    DataTable dtTemplet = tmpTemplet.GetListByClsno(clsno);
                    if (dtTemplet.Rows.Count > 0)
                    {
                        DataRow drTemplet = dtTemplet.Rows[0];
                        t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                        t_createpath = t_createpath + drTemplet["createpath"].ToString();
                        t_showfile = drTemplet["showfile"].ToString();
                    }

                    model.no = PlugNT.Common.Utils.GetDateTimeCode() + Session.SessionID.GetHashCode().ToString();
                    model.images = images;
                    model.title = title;
                    model.subtitle = subtitle;
                    model.keyword = this.keyword.Text;//默认值
                    model.description = this.txtzhaiyao.Text;
                    model.clsno = clsno;
                    model.clslist = clslist;  // curChannel.GetClslistByNo(clsno, false);
                    model.clsname = this.ddlMenu.SelectedItem.Text.Replace(" ", "").Replace("├", "");
                    model.contents = this.txtContext.Text; //editbox.Text;
                    model.jumpurl = jumpurl;
                    model.info = this.txtinfor.Text;
                    model.author = this.txtauthor.Text;
                    model.url = this.txturl.Text;
                    int tip = 0;
                    int.TryParse(this.txtdig.Text.Trim(), out tip);
                    model.tip = tip;
                    model.tag = this.txttag.Text;
                    int hits = 0;
                    int.TryParse(this.txthits.Text.Trim(), out hits);
                    model.hits = hits;
                    model.orders = int.Parse(txtorders.Text.Trim());
                    model.commend = this.commend.Checked;
                    model.stick = this.stick.Checked;
                    model.publish = this.publish.Checked;
                    model.addtime = DateTime.Now;
                    model.createpath = (createpath == "") ? t_createpath : "/" + createpath.Trim('/') + "/";
                    model.pagename = txtpagename.Text.Trim();

                    if (!"".Equals(jumpurl))
                    {
                        model.jumpurl = createpath;
                        model.createpath = jumpurl;
                        model.pagename = "' target='_blank' p='";
                    }
                    //设置扩展字段
                    if (Request.Form != null)
                    {
                        foreach (string s in Request.Form.Keys)
                        {
                            if (s.StartsWith("extfield_"))
                            {
                                FieldModel finfo = new FieldModel();
                                string[] sArr = s.Split('_');
                                finfo.fieldName = sArr[1];
                                finfo.fieldType = sArr[2];
                                finfo.fieldValue = Request.Form[s];
                                model.AppExtField(finfo);
                            }
                        }
                    }

                    //录入数据
                    if (curArticle.Add(model))
                    {
                        string sid = curArticle.GetId(model.no);
                        int tid = int.Parse(sid);
                        //更新页面名
                        if (model.pagename == "")
                        {
                            string tmpFileName = PlugNT.Common.Utils.GetFileName(t_showfile);
                            int tmpFlag = tmpFileName.LastIndexOf(".");
                            tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                            string cmsPreShow = tmpFileName;
                            model.pagename = sid;
                            //model.pagename = cmsPreShow + sid;
                        }

                        model.id = tid;
                        DataRow dr = curArticle.GetPreviousDataRow(model.id, model.clsno);
                        if (dr != null)
                        {
                            string hurl = (dr["jumpurl"].ToString() != "") ? dr["jumpurl"].ToString() : dr["createpath"].ToString() + dr["pagename"].ToString() + ".shtml";
                            model.previouspage = "<a id=\"pntPrevious" + model.id.ToString() + "\" href=\"" + hurl + "\">" + dr["title"].ToString() + "</a>";
                        }
                        dr = curArticle.GetNextDataRow(model.id, model.clsno);
                        if (dr != null)
                        {
                            string hurl = (dr["jumpurl"].ToString() != "") ? dr["jumpurl"].ToString() : dr["createpath"].ToString() + dr["pagename"].ToString() + ".shtml";
                            model.nextpage = "<a id=\"pntNext" + model.id.ToString() + "\" href=\"" + hurl + "\">" + dr["title"].ToString() + "</a>";

                            string tmpHurl = (model.jumpurl != "") ? model.jumpurl : model.createpath + model.pagename + ".shtml";
                            string tmpPreviouspage = "<a id=\"pntPrevious" + dr["id"].ToString() + "\" href=\"" + tmpHurl + "\">" + model.title + "</a>";
                            curArticle.UpdatePreviousPage(int.Parse(dr["id"].ToString()), tmpPreviouspage);
                        }
                        flag = curArticle.UpdatePart(model);

                        //发布
                        if (this.publish.Checked)
                        {
                            if (isbindtmp)
                            {
                                HtmlBuilder html = new HtmlBuilder();
                                html.TablePostFix = currpostfix;

                                if ("".Equals(jumpurl))
                                {
                                    string error = PageBuilder.CreateShowHtml(html, sid, model.pagename, model.createpath, t_showfile, clsno);

                                    if (error != "")
                                    {
                                        if (flag)
                                        {
                                            errorMessage = "发布失败：" + error + "，录入新闻--<b>[" + title + "]</b>--成功！&z=no";
                                        }
                                        else
                                        {
                                            errorMessage = "发布失败：" + error + "，录入新闻--<b>[" + title + "]</b>--失败！&z=no";
                                        }
                                        flag = false;
                                    }
                                }
                            }
                        }

                    }
                }
                else
                {
                    errorMessage = "修改新闻--<b>[" + title + "]</b>--失败，请选择正确的栏目！&z=no";
                    flag = false;
                }
            }
            else
            {
                errorMessage = "修改新闻--<b>[" + title + "]</b>--失败，不存在数据表！&z=no";
                flag = false;
            }

            if (flag)
            {
                if (Sys.Info.articleupdated == false)
                {
                    Sys.Info.articleupdated = true;
                    Sys.UpdateArticleupdated();
                }
                Response.Redirect("../Message.aspx?message=录入新闻--<b>[" + title + "]</b>--成功！&z=yes");
            }
            else
            {
                Response.Redirect("../Message.aspx?message=" + errorMessage);
            }

        }

        #region 数据绑定
        private void Data_bind()
        {

            txtpic.Attributes.Add("onmouseover", "ShowPic(true);");
            txtpic.Attributes.Add("onmouseout", "ShowPic(false);");
            txtcreatepath.Attributes.Add("onpropertychange", "SwapTextColor('txtcreatepath');");
            txtpagename.Attributes.Add("onpropertychange", "SwapTextColor('txtpagename');");



            #region 绑定栏目

            //栏目
            TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
            if (tinfo != null)
            {
                DataTable dt = new Channel().GetOrderList(tinfo.bindclslist);
                this.ddlMenu.Items.Clear();
                this.ddlMenu.Items.Add(new ListItem("请选择所属栏目", ""));
                foreach (DataRow dr in dt.Rows)
                {
                    int ClassTj = Convert.ToInt32(dr["clslistlen"]);
                    string tmpClsno = dr["clsno"].ToString().Trim();
                    string tmpClslist = dr["clslist"].ToString().Trim();
                    string showfile = dr["showfile"].ToString().Trim();
                    string ClassName = dr["clsname"].ToString().Trim();
                    if (ClassTj != 1)
                    {
                        ClassName = "├ " + ClassName;
                        ClassName = PlugNT.Common.Utils.StringOfChar(ClassTj - 1, "　") + ClassName;
                    }
                    tmpClslist = tmpClslist + "-" + tmpClsno + "-" + (showfile == "" ? "null" : bindtag);
                    ListItem li = new ListItem(ClassName, tmpClslist);
                    if (showfile == "")
                    {
                        li.Attributes.Add("style", "background-color:#ffdfe2;");
                    }
                    this.ddlMenu.Items.Add(li);
                }
            }

            #endregion

            #region 绑定扩展字段
            DataTable dt3 = curField.GetList(currpostfix);
            if (dt3.Rows.Count > 0)
            {
                bool brFlag = false;
                foreach (DataRow dr in dt3.Rows)
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl span = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                    span.InnerHtml = (brFlag ? "<br /><br />" : "") + dr["title"].ToString() + ": <br />";
                    brFlag = true;
                    div_extend.Controls.Add(span);

                    TextBox tmpTextBox = null;
                    string htmldepth = dr["htmldepth"].ToString();
                    switch (dr["htmltype"].ToString())
                    {
                        case FieldHtmlType.textType:
                            tmpTextBox = new TextBox();
                            if (htmldepth != "")
                            {
                                string[] hdepth = htmldepth.Split('*');
                                string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                tmpTextBox.Attributes.Add("style", widthString + heightString);
                            }
                            tmpTextBox.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                            tmpTextBox.Text = dr["defaultvalue"].ToString();
                            div_extend.Controls.Add(tmpTextBox);
                            break;
                        case FieldHtmlType.textareaType:
                            tmpTextBox = new TextBox();
                            tmpTextBox.TextMode = TextBoxMode.MultiLine;
                            if (htmldepth != "")
                            {
                                string[] hdepth = htmldepth.Split('*');
                                string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                tmpTextBox.Attributes.Add("style", widthString + heightString);
                            }
                            tmpTextBox.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                            tmpTextBox.Text = dr["defaultvalue"].ToString();
                            div_extend.Controls.Add(tmpTextBox);
                            break;
                        case FieldHtmlType.dropdownlistType:
                            DropDownList tmpDropDownList = new DropDownList();
                            if (htmldepth != "")
                            {
                                string[] hdepth = htmldepth.Split('*');
                                string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                tmpDropDownList.Attributes.Add("style", widthString + heightString);
                            }
                            tmpDropDownList.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                            DataTable dt4 = null;
                            if (Boolean.Parse(dr["isbindsub"].ToString()))
                            {
                                dt4 = curCategory.GetOrderList(dr["bindclslist"].ToString());
                            }
                            else
                            {
                                dt4 = curCategory.GetOrderSubList(dr["bindclslist"].ToString());
                            }
                            foreach (DataRow dr2 in dt4.Rows)
                            {
                                int ClassTj = Convert.ToInt32(dr2["clslistlen"]);
                                string tmpClslist = dr2["clslist"].ToString().Trim();
                                string ClassName = dr2["clsname"].ToString().Trim();
                                ListItem li = null;
                                if (ClassTj == 1)
                                {
                                    li = new ListItem(ClassName, tmpClslist);
                                }
                                else
                                {
                                    ClassName = "├ " + ClassName;
                                    ClassName = PlugNT.Common.Utils.StringOfChar(ClassTj - 1, "　") + ClassName;
                                    li = new ListItem(ClassName, tmpClslist);
                                }
                                tmpDropDownList.Items.Add(li);
                            }



                            tmpDropDownList.SelectedValue = dr["defaultvalue"].ToString();
                            div_extend.Controls.Add(tmpDropDownList);
                            break;
                        case FieldHtmlType.editerType:
                            string tmpEditerID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                            System.Web.UI.HtmlControls.HtmlGenericControl editer = new System.Web.UI.HtmlControls.HtmlGenericControl("span");

                            StringBuilder sb2 = new StringBuilder();
                            sb2.AppendLine("<textarea id=\"" + tmpEditerID + "\" name=\"" + tmpEditerID + "\">" + dr["defaultvalue"].ToString() + "</textarea>");
                            sb2.AppendLine("<script type=\"text/javascript\">");
                            sb2.AppendLine("var oFCK" + tmpEditerID + " = new FCKeditor(\"" + tmpEditerID + "\"); ");
                            sb2.AppendLine("oFCK" + tmpEditerID + ".BasePath = \"/Tools/Editer/fck/\"; ");
                            if (htmldepth != "")
                            {
                                string[] hdepth = htmldepth.Split('*');
                                if (hdepth[0] != "")
                                {
                                    sb2.AppendLine("oFCK" + tmpEditerID + ".Width = " + hdepth[0] + "; ");
                                }
                                if (hdepth[1] == "")
                                {
                                    sb2.AppendLine("oFCK" + tmpEditerID + ".Height = " + hdepth[1] + "; ");
                                }
                            }
                            sb2.AppendLine("oFCK" + tmpEditerID + ".ToolbarSet = \"CustomSimple\";  ");
                            sb2.AppendLine("oFCK" + tmpEditerID + ".ReplaceTextarea();");
                            sb2.AppendLine("</script>");
                            editer.InnerHtml = sb2.ToString();

                            div_extend.Controls.Add(editer);
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                System.Web.UI.HtmlControls.HtmlGenericControl editer = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                editer.InnerHtml = "暂无扩展字段！";
                div_extend.Controls.Add(editer);
            }
            #endregion

        }


        #endregion

    }
}

